package com.huanbao.oil.app.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.google.gson.Gson;
import com.huanbao.oil.app.R;
import com.huanbao.oil.app.adapter.YXcanshuAdapter;
import com.huanbao.oil.app.adapter.YXjiluAdapter;
import com.huanbao.oil.app.application.MessageEvent;
import com.huanbao.oil.app.commons.DateUtil;
import com.huanbao.oil.app.commons.JsonUtil;
import com.huanbao.oil.app.commons.UtilsLog;
import com.huanbao.oil.app.model.BaoJingSearchModel;
import com.huanbao.oil.app.model.YXJiLuModel;
import com.huanbao.oil.app.model.YunXingCanShuResultModel;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class YunXingJiLuFragment extends Fragment {
    public static final String BUNDLE_TITLE = "title";

    @BindView(R.id.yuxingjilu_fragment_listview)
    ListView yuxingjiluFragmentListview;
    @BindView(R.id.yuxingjilu_tv_1)
    TextView yuxingjiluTv1;
    @BindView(R.id.yuxingjilu_tv_start_time)
    TextView yuxingjiluTvStartTime;
    @BindView(R.id.yuxingjilu_tv_2)
    TextView yuxingjiluTv2;
    @BindView(R.id.yuxingjilu_tv_end_time)
    TextView yuxingjiluTvEndTime;
    @BindView(R.id.yuxingjilu_fragment_btn_end)
    Button yuxingjiluFragmentBtnEnd;
    @BindView(R.id.yuxingjilu_rl)
    RelativeLayout yuxingjiluRl;
    Unbinder unbinder;

    private String mTitle = "DefaultValue";
    private MainActivity mainActivity;
    private YXcanshuAdapter canShuAdapter;
    private YXjiluAdapter yunXing_jiLuAdapter;
    String startTime = "", endTime = "";
    String startDate = "2015-05-16 15:03:17", endDate = "2020-05-16 15:03:17";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mainActivity = (MainActivity) getActivity();
        EventBus.getDefault().register(this);
        Bundle arguments = getArguments();
        if (arguments != null) {
            mTitle = arguments.getString(BUNDLE_TITLE);
        }
        View v = inflater.inflate(R.layout.yunxingjilu_fragment, container, false);
        unbinder = ButterKnife.bind(this, v);
        return v;
    }

    @Override
    public void onResume() {
        super.onResume();
        yunXing_jiLuAdapter = new YXjiluAdapter(mainActivity, null);
        yuxingjiluFragmentListview.setAdapter(canShuAdapter);
        BaoJingSearchModel model = new BaoJingSearchModel();
        model.setCmd_type(11);
//                    model.setCmd_type(5);
        model.setBegin_time(startDate);
        model.setEnd_time(endDate);
        Gson gson = new Gson();
        mainActivity.jsonStr = gson.toJson(model);
        mainActivity.openDoor(mainActivity.jsonStr);
    }

    public static YunXingJiLuFragment newInstance(String title) {
        Bundle bundle = new Bundle();
        bundle.putString(BUNDLE_TITLE, title);
        YunXingJiLuFragment fragment = new YunXingJiLuFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        EventBus.getDefault().unregister(this);
    }

    @OnClick({R.id.yuxingjilu_tv_end_time, R.id.yuxingjilu_tv_start_time, R.id.yuxingjilu_fragment_btn_end})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.yuxingjilu_tv_start_time:
                //时间选择器
                TimePickerView pvTime = new TimePickerBuilder(mainActivity, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {//选中事件回调
                        yuxingjiluTvStartTime.setText(DateUtil.DateToStrHM3(date));
                        startDate = DateUtil.DateToStrHM3(date);
                    }
                })
                        .setType(new boolean[]{true, true, true, true, true, true})//分别对应年月日时分秒，默认全部显示
                        .setCancelText("取消")//取消按钮文字
                        .setSubmitText("确定")//确认按钮文字
                        .setLabel("年", "月", "日", "时", "分", "秒")
                        .build();
                pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
                pvTime.show();
                break;
            case R.id.yuxingjilu_tv_end_time:
                //时间选择器
                TimePickerView pvTime2 = new TimePickerBuilder(mainActivity, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {//选中事件回调
                        yuxingjiluTvEndTime.setText(DateUtil.DateToStrHM3(date));
                        endDate = DateUtil.DateToStrHM3(date);
                    }
                })
                        .setType(new boolean[]{true, true, true, true, true, true})//分别对应年月日时分秒，默认全部显示
                        .setCancelText("取消")//取消按钮文字
                        .setSubmitText("确定")//确认按钮文字
                        .setLabel("年", "月", "日", "时", "分", "秒")
                        .build();
                pvTime2.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
                pvTime2.show();
                break;
            case R.id.yuxingjilu_fragment_btn_end:
                if (!TextUtils.isEmpty(startDate) && !TextUtils.isEmpty(endDate)) {
                    BaoJingSearchModel model = new BaoJingSearchModel();
                    model.setCmd_type(11);
//                    model.setCmd_type(5);
                    model.setBegin_time(startDate);
                    model.setEnd_time(endDate);
                    Gson gson = new Gson();
                    mainActivity.jsonStr = gson.toJson(model);
                    mainActivity.openDoor(mainActivity.jsonStr);
                } else {
                    Toast.makeText(mainActivity, "时间不能为空", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }

    List<YXJiLuModel> modelList = new ArrayList<>();


    @Subscribe(threadMode = ThreadMode.ASYNC, sticky = true)
    public void onMessageEvent(MessageEvent event) {
        if (mainActivity.TCP_MODE == 2) {
            if (!TextUtils.isEmpty(event.getMessage()) && !"{}".equals(event.getMessage())
                    && !"{[]}".equals(event.getMessage())) {
                try {
                    JSONObject jsonObject = new JSONObject(event.getMessage());
                    int cmd_type = 0;
                    if (jsonObject.has("cmd_type")) {
                        cmd_type = jsonObject.getInt("cmd_type");
                        UtilsLog.e("运行记录===cmd_type==" + cmd_type);
                    }
//                    if (cmd_type == 10) {
                        if(cmd_type==12){
                        UtilsLog.e("运行记录===进入解析==");
                        if (jsonObject.getString("records") != "[]" && !TextUtils.isEmpty(jsonObject.getString("records"))) {
                            modelList = JsonUtil.stringToArray(jsonObject.getString("records"), YXJiLuModel[].class);
                            if (modelList != null && modelList.size() > 0) {
                                UtilsLog.e("运行记录===records==");
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        UtilsLog.e("运行记录===handler==");
                                        Message msg = new Message();
                                        msg.obj = modelList;
                                        handler.sendMessage(msg);
                                    }
                                }).start();
                            } else {
                                UtilsLog.e("运行记录===零条数据==");
                            }
                        } else {
                            UtilsLog.e("运行记录===解析数据异常==");
                        }
                    } else {
                        UtilsLog.e("运行记录===cmd_type!==10");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    UtilsLog.e("运行记录===进入解析==" + e.getMessage());
                }
            } else {
                UtilsLog.e("运行记录===没有获取到数据==");
            }
        } else {
            UtilsLog.e("运行记录===00000000==");
        }
    }

    private Handler handler = new Handler() {
        //这是默认的方法
        @Override
        public void handleMessage(Message msg) {
            if (msg.obj != null) {
                yunXing_jiLuAdapter = new YXjiluAdapter(mainActivity, (List<YXJiLuModel>) msg.obj);
                yuxingjiluFragmentListview.setAdapter(yunXing_jiLuAdapter);
                yuxingjiluFragmentListview.setVisibility(View.VISIBLE);
                UtilsLog.e("运行记录===1111111111==");
            } else {
                UtilsLog.e("运行记录===22222222222==");
                yuxingjiluFragmentListview.setVisibility(View.GONE);
            }
        }
    };
//    @Subscribe(threadMode = ThreadMode.ASYNC,sticky = false)
//    public void YunXingCanShu(MessageEvent event) {
//        UtilsLog.e("记录===接收到的数据=="+event.getMessage());
//        UtilsLog.e("记录=="+mainActivity.TCP_MODE );
//
//    }
}
